package com.lu.manage.modular.system.model.server;

import com.lu.manage.core.utils.DateTimeUtils;
import com.lu.manage.modular.system.model.server.utils.Arith;
import com.lu.manage.modular.system.model.server.utils.IpUtils;
import org.apache.commons.lang3.time.DateUtils;
import oshi.SystemInfo;
import oshi.hardware.CentralProcessor;
import oshi.hardware.CentralProcessor.TickType;
import oshi.hardware.GlobalMemory;
import oshi.hardware.HardwareAbstractionLayer;
import oshi.software.os.FileSystem;
import oshi.software.os.OSFileStore;
import oshi.software.os.OperatingSystem;
import oshi.util.Util;

import java.lang.management.ManagementFactory;
import java.net.UnknownHostException;
import java.util.*;

/**
 * 服务器相关信息
 *
 * @author ruoyi
 */
public class Server
{
    private static final int OSHI_WAIT_SECOND = 1000;

    /**
     * CPU相关信息
     */
    private Cpu cpu = new Cpu();

    /**
     * 內存相关信息
     */
    private Mem mem = new Mem();

    /**
     * JVM相关信息
     */
    private Jvm jvm = new Jvm();

    /**
     * 服务器相关信息
     */
    private Sys sys = new Sys();

    /**
     * 磁盘相关信息
     */
    private List<SysFile> sysFiles = new LinkedList<SysFile>();

    public Cpu getCpu()
    {
        return cpu;
    }

    public void setCpu(Cpu cpu)
    {
        this.cpu = cpu;
    }

    public Mem getMem()
    {
        return mem;
    }

    public void setMem(Mem mem)
    {
        this.mem = mem;
    }

    public Jvm getJvm()
    {
        return jvm;
    }

    public void setJvm(Jvm jvm)
    {
        this.jvm = jvm;
    }

    public Sys getSys()
    {
        return sys;
    }

    public void setSys(Sys sys)
    {
        this.sys = sys;
    }

    public List<SysFile> getSysFiles()
    {
        return sysFiles;
    }

    public void setSysFiles(List<SysFile> sysFiles)
    {
        this.sysFiles = sysFiles;
    }

    public static void main(String[] args) {
        try {
            Server server = new Server();
            Cpu cpu = server.getCpuInfo();
            Mem mem = server.getMemInfo();
            Jvm jvm = server.getJvmInfo();
            Sys sys = server.getSysInfo();
            List<SysFile> sysFiles = server.getSysFilesInfo();
            System.out.println("111");
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
    }

    public static Server serverData(){
        Server server = new Server();
        try {
            Cpu cpu = server.getCpuInfo();
            Mem mem = server.getMemInfo();
            Jvm jvm = server.getJvmInfo();
            Sys sys = server.getSysInfo();
            List<SysFile> sysFiles = server.getSysFilesInfo();
            server.setCpu(cpu);
            server.setMem(mem);
            server.setJvm(jvm);
            server.setSys(sys);
            server.setSysFiles(sysFiles);

        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        return server;
    }

    public static Server cpuMemJvm(){
        Server server = new Server();
        try {
            Cpu cpu = server.getCpuInfo();
            Mem mem = server.getMemInfo();
            Jvm jvm = server.getJvmInfo();
            server.setCpu(cpu);
            server.setMem(mem);
            server.setJvm(jvm);
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        return server;
    }

    /**
     * 设置CPU信息
     */
    public Cpu getCpuInfo() {
        SystemInfo si = new SystemInfo();
        HardwareAbstractionLayer hal = si.getHardware();
        CentralProcessor processor = hal.getProcessor();
        // CPU信息
        long[] prevTicks = processor.getSystemCpuLoadTicks();
        Util.sleep(OSHI_WAIT_SECOND);
        long[] ticks = processor.getSystemCpuLoadTicks();
        long nice = ticks[TickType.NICE.getIndex()] - prevTicks[TickType.NICE.getIndex()];
        long irq = ticks[TickType.IRQ.getIndex()] - prevTicks[TickType.IRQ.getIndex()];
        long softirq = ticks[TickType.SOFTIRQ.getIndex()] - prevTicks[TickType.SOFTIRQ.getIndex()];
        long steal = ticks[TickType.STEAL.getIndex()] - prevTicks[TickType.STEAL.getIndex()];
        long cSys = ticks[TickType.SYSTEM.getIndex()] - prevTicks[TickType.SYSTEM.getIndex()];
        long user = ticks[TickType.USER.getIndex()] - prevTicks[TickType.USER.getIndex()];
        long iowait = ticks[TickType.IOWAIT.getIndex()] - prevTicks[TickType.IOWAIT.getIndex()];
        long idle = ticks[TickType.IDLE.getIndex()] - prevTicks[TickType.IDLE.getIndex()];
        long totalCpu = user + nice + cSys + idle + iowait + irq + softirq + steal;

        double total = Arith.round(Arith.mul((double)totalCpu, 100), 2);
        double sys = Arith.round(Arith.mul((double) cSys / totalCpu, 100), 2);
        double used = Arith.round(Arith.mul((double)user / totalCpu, 100), 2);
        double wait = Arith.round(Arith.mul((double)iowait / totalCpu, 100), 2);
        double free = Arith.round(Arith.mul((double)idle / totalCpu, 100), 2);
        Cpu cpu = new Cpu();
        cpu.setCpuNum(processor.getLogicalProcessorCount());
        cpu.setTotal(total);
        cpu.setSys(sys);
        cpu.setUsed(used);
        cpu.setWait(wait);
        cpu.setFree(free);
        return cpu;
    }

    /**
     * 设置内存信息
     */
    public Mem getMemInfo() {
        SystemInfo si = new SystemInfo();
        HardwareAbstractionLayer hal = si.getHardware();
//        setCpuInfo(hal.getProcessor());
        GlobalMemory memory = hal.getMemory();
        Mem mem = new Mem();
        mem.setTotal(Arith.div(memory.getTotal(), (1024 * 1024 * 1024), 2));
        mem.setUsed(Arith.div(memory.getTotal() - memory.getAvailable(), (1024 * 1024 * 1024), 2));
        mem.setFree(Arith.div(memory.getAvailable(), (1024 * 1024 * 1024), 2));
        mem.setUsage(Arith.mul(Arith.div(memory.getTotal() - memory.getAvailable(), memory.getTotal(), 4), 100));
        return mem;
    }

    /**
     * 设置服务器信息
     */
    public Sys getSysInfo() {
        Properties props = System.getProperties();
        Sys sys = new Sys();
        sys.setComputerName(IpUtils.getHostName());
        sys.setComputerIp(IpUtils.getHostIp());
        sys.setOsName(props.getProperty("os.name"));
        sys.setOsArch(props.getProperty("os.arch"));
        sys.setUserDir(props.getProperty("user.dir"));
        return sys;
    }

    /**
     * 设置Java虚拟机
     * @return
     */
    public Jvm getJvmInfo() throws UnknownHostException {
        Properties props = System.getProperties();
        Jvm jvm = new Jvm();
        double total = Runtime.getRuntime().totalMemory();
        double free = Runtime.getRuntime().freeMemory();
        jvm.setTotal(total);
        jvm.setMax(Runtime.getRuntime().maxMemory());
        jvm.setFree(free);
        jvm.setUsed(Arith.div(total - free, (1024 * 1024), 2));
        jvm.setUsage(Arith.mul(Arith.div(total - free, total, 4), 100));
        jvm.setVersion(props.getProperty("java.version"));
        jvm.setHome(props.getProperty("java.home"));
        jvm.setName(ManagementFactory.getRuntimeMXBean().getVmName());
        jvm.setStartTime(DateTimeUtils.formatDate(DateTimeUtils.getServerStartDate(), DateTimeUtils.YYYY_MM_DD_HH_MM_SS));
        jvm.setRunTime(DateTimeUtils.getDatePoor(new Date(), DateTimeUtils.getServerStartDate()));
        return jvm;
    }

    /**
     * 设置磁盘信息
     */
    public List<SysFile> getSysFilesInfo() {
        SystemInfo si = new SystemInfo();
        OperatingSystem os = si.getOperatingSystem();
        List<SysFile> sysFiles = new ArrayList<>();
        FileSystem fileSystem = os.getFileSystem();
        OSFileStore[] fsArray = fileSystem.getFileStores();
        for (OSFileStore fs : fsArray)
        {
            long free = fs.getUsableSpace();
            long total = fs.getTotalSpace();
            long used = total - free;
            SysFile sysFile = new SysFile();
            sysFile.setDirName(fs.getMount());
            sysFile.setSysTypeName(fs.getType());
            sysFile.setTypeName(fs.getName());
            sysFile.setTotal(convertFileSize(total));
            sysFile.setFree(convertFileSize(free));
            sysFile.setUsed(convertFileSize(used));
            sysFile.setUsage(Arith.mul(Arith.div(used, total, 4), 100));
            sysFiles.add(sysFile);
        }
        return sysFiles;
    }

    /**
     * 字节转换
     *
     * @param size 字节大小
     * @return 转换后值
     */
    public String convertFileSize(long size)
    {
        long kb = 1024;
        long mb = kb * 1024;
        long gb = mb * 1024;
        if (size >= gb)
        {
            return String.format("%.1f GB", (float) size / gb);
        }
        else if (size >= mb)
        {
            float f = (float) size / mb;
            return String.format(f > 100 ? "%.0f MB" : "%.1f MB", f);
        }
        else if (size >= kb)
        {
            float f = (float) size / kb;
            return String.format(f > 100 ? "%.0f KB" : "%.1f KB", f);
        }
        else
        {
            return String.format("%d B", size);
        }
    }
}
